package org.ccay.log.connection.impl;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;


import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;
import org.ccay.core.request.IRequestContext;
import org.ccay.core.request.IUserPrincipal;
import org.ccay.core.request.impl.RequestContextConstants;
import org.ccay.core.request.impl.RequestContextManager;
import org.ccay.log.connection.IDatabaseConnectionLog;

/**
 * Web Server 连接池的对象
 * 
 * @author chaowangbang
 * 
 */
public class LocalDatabaseConnectionLog implements IDatabaseConnectionLog {
	
	private static ILogger logger = CcayLoggerFactory.getLogger(LocalDatabaseConnectionLog.class);
	/**
	 * 记录Connection中日志
	 * (non-Javadoc)
	 * @see org.ccay.log.connection.IDatabaseConnectionLog#log(java.sql.Connection)
	 */
	public void log(Connection conn) {
		 
		try {
		 
			//获取请求上下文
			IRequestContext context = RequestContextManager.getCurrent(true);
			if(context == null){
				return;
			}
			//获取当前登录用户
			 IUserPrincipal user = context.getUser();
			if(user == null ){
				return ;
			}
			StringBuilder userOPInfo = new StringBuilder(user.getUserName());
			userOPInfo.append(":");
			//获取当前用户操作的资源地址
			String url = (String) context.getItem(RequestContextConstants.KEY_URI);
			userOPInfo.append(url);
				 
			//存储64位长度
			String userInfo = userOPInfo.toString();
			if (userInfo.length() > 64) {
				userInfo = userInfo.substring(0, 64);
			}
			logger.debug("User Information:"+userInfo);
	        Connection conInstance = this.getConnection(conn);
			
			if(conInstance == null){
				return ;
			}
			
//			if(conInstance instanceof OracleConnection) {
//				OracleConnection oracleConn= (OracleConnection) conInstance;
//			
//				//存储用户信息 
//				String[] metrics = oracleConn.getEndToEndMetrics();
//				if (metrics == null) {
//					metrics = new String[OracleConnection.END_TO_END_STATE_INDEX_MAX];
//				}
//				metrics[OracleConnection.END_TO_END_CLIENTID_INDEX] = userInfo;
//				oracleConn.setEndToEndMetrics(metrics, (short) 0);
//			}
			
		//打印异常信息
//		} catch (SQLException e) {
//			logger.error(e);
		}catch(RuntimeException e){
			logger.error(e);
		} 
	}
	/**
	 * 获取Connection对象
	 * @param conn
	 * @return
	 */
	private Connection getConnection(Connection conn) {
		@SuppressWarnings("rawtypes")
		Class clazz = conn.getClass(); 
		Field delegateField;
		try {
			delegateField = clazz.getDeclaredField("delegate");
			delegateField.setAccessible(true);
			Connection poolConnection  = (Connection) delegateField.get(conn); 
			if(poolConnection == null){
				return  null;
			}
			
			Method method = poolConnection.getClass().getMethod("getDelegate");
			
			return (Connection) method.invoke(poolConnection); 

		}catch (NoSuchFieldException e) {
			logger.error(e);
		} catch (IllegalAccessException e) {
			logger.error(e);
		} catch (InvocationTargetException e) {
			logger.error(e);
		} catch (NoSuchMethodException e) {
			logger.error(e);
		}  
		return null;
	}
}
